#include "ShareMemoryBase.h"

ShareMemoryBase::ShareMemoryBase( LPCTSTR pName, UINT uSize, DWORD dwAccess /*= PAGE_READWRITE */ ) :
m_hMapFile(NULL),
m_buffer(NULL),
m_errCode(0),
m_Mutex(NULL)
{
	TCHAR wcMutexName[256] = {0};
	m_hMapFile = CreateFileMapping(
		INVALID_HANDLE_VALUE,    // use paging file
		NULL,                    // default security
		dwAccess,                // read/write access
		0,                       // maximum object size (high-order DWORD)
		uSize,                   // maximum object size (low-order DWORD)
		pName);                  // name of mapping object

	if (m_hMapFile == NULL)
	{
		m_errCode = GetLastError();
		return;
	}

	m_buffer = (void*) MapViewOfFile(m_hMapFile,   // handle to map object
		FILE_MAP_ALL_ACCESS, // read/write permission
		0,
		0,
		uSize);

	if (m_buffer == NULL)
	{
		m_errCode = GetLastError();
		CloseHandle(m_hMapFile);
		m_hMapFile = NULL;

		return;
	}

	_tcscpy(wcMutexName, pName);
	_tcscat(wcMutexName, L"_MUTEX");
	m_Mutex = CreateMutex(NULL, false, wcMutexName);

}

ShareMemoryBase::~ShareMemoryBase( void )
{
	if (m_buffer != NULL)
	{
		UnmapViewOfFile(m_buffer);
		m_buffer = NULL;
	}
	if (m_hMapFile != NULL)
	{
		CloseHandle(m_hMapFile);
		m_hMapFile = NULL;
	}
	if (m_Mutex != NULL)
	{
		CloseHandle(m_Mutex);
		m_Mutex = NULL;
	}
}

void* ShareMemoryBase::GetShareMemoryBuffer()
{
	return m_buffer;
}

int ShareMemoryBase::GetErrorCode() const
{
	return m_errCode;
}

void ShareMemoryBase::Lock()
{
	if (m_Mutex != NULL)
	{
		WaitForSingleObject(m_Mutex, INFINITE);
	}
}

void ShareMemoryBase::UnLock()
{
	if (m_Mutex != NULL)
	{
		ReleaseMutex(m_Mutex);
	}
}
